package com.xxxx.yoyo.adminweb;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.service.IUserService;
import com.xxxx.yoyo.service.impl.UserServiceImpl;
import com.xxxx.yoyo.util.SafeUtil;


@WebServlet("/admin/userModifyPwd")
public class UserModifyPasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IUserService userService = new UserServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取请求参数：id
		String userIdstr = request.getParameter("id");
		int userId = Integer.parseInt (userIdstr);
		
		//根据用户id获取用户信息
		User user = userService.getUserById(userId);
		//把user存入上equest中，供/admin/user_modifyPwd.jsp页面使用
		request.setAttribute("user", user);
		
		//设置导航条上的[客户管理]处于选中状态
		request.setAttribute("flag", 2);
		
		//请求转发，跳转到/admin/user modifyPwd.jsp页面
		request.getRequestDispatcher("/admin/user_modifyPwd.jsp").forward(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置导航条上的[客户管理]处于选中状态
		request.setAttribute("flag", 2);
	
		//获取前端传递过来的参数d,password
		String userIdstr = request.getParameter("id");
		int userId = Integer.parseInt(userIdstr);
		String password = request.getParameter("password");//明文密码
		
		//根据用户id获取用户信息
		User user = userService.getUserById(userId);
		//对接收到的密码进行加密
		String pwd = SafeUtil.encode(password);
		//修改用户的密码
		user.setPassword(pwd);
		
		//更新数据库user信息
		boolean isSuccess = userService.updateUser(user);
		if(isSuccess) {//修改成功
			//提示修改成功
			request.setAttribute("msg","密码修改成功！");
		}else {
			//提示错误信息
			request.setAttribute("msg","密码修改失败！");
		}
		//把user存入上equest中，供/admin/user_modifyPwd.jsp页面使用
		request.setAttribute("user", user);
		
		//请求转发，跳转到/admin/user modifyPwd.jsp页面
		request.getRequestDispatcher("/admin/user_modifyPwd.jsp").forward(request,response);	
	
		
		
	}

}
